//
//  PhotoBrowerViewCell.swift
//  Weibo
//
//  Created by 孙明海 on 16/2/19.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD


protocol PhotoBrowerViewCellDelegate: NSObjectProtocol {
    func PhotoBrowerViewCellDidTapImage()
}

class PhotoBrowerViewCell: UICollectionViewCell {
    weak var photoDelegate: PhotoBrowerViewCellDelegate?
    
    //MARK: - 监听方法
    @objc private func tapImage() {
        photoDelegate?.PhotoBrowerViewCellDidTapImage()
    }
    
    
    var imageURL: NSURL? {
        didSet {
            guard let url = imageURL else {
                return
            }
            resetScrollView()
            // 设置占位图片
            let placeImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString)
            setPlaceHoder(placeImage)
            
            print(bmiddleURL(url))
            
            imageView.sd_setImageWithURL(bmiddleURL(url), placeholderImage: nil, options: [SDWebImageOptions.RefreshCached,SDWebImageOptions.RetryFailed], progress: { (current, total) -> Void in
                    self.placeHoder.progress = CGFloat(current) / CGFloat(total)
                }) { (image, _, _, _) -> Void in
                    
                    if image == nil {
                       SVProgressHUD.showInfoWithStatus("您的网络不给力!")
                        return
                    }
                    
                    self.placeHoder.hidden = true
                    self.setImageViewPosition(image)
            }
        }
    }
    /// 设置占位图片
    ///
    /// - parameter image: 占位图片
    private func setPlaceHoder(image: UIImage?) {
        placeHoder.hidden = false
        placeHoder.image = image
        placeHoder.sizeToFit()
        placeHoder.center = scrollView.center
    }
    
    /// 重新设置scrollView 的属性
    private func resetScrollView() {
        
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
        // 充值 imageView 的内容属性
        imageView.transform = CGAffineTransformIdentity
    }
    /// 设置 imageView 的位置
    ///
    /// - parameter image: image
    private func setImageViewPosition(image: UIImage) {
        let size = displaySize(image)
        
        if size.height < scrollView.bounds.height {
            imageView.frame.size = size
            imageView.center = scrollView.center
        } else {
            imageView.frame = CGRectMake(0, 0, size.width, size.height)
            scrollView.contentSize = size
        }
    }
    
    private func displaySize(image: UIImage) -> CGSize {
        let width = scrollView.bounds.width
        let height = image.size.height * width / image.size.width
        return CGSize(width: width, height: height)
    }
    /// 返回中等尺寸图片 URL
    ///
    /// - parameter url: 小图 URL
    ///
    /// - returns: 中等尺寸 URL
    private func bmiddleURL(url: NSURL) -> NSURL {
        var urlString = url.absoluteString
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        return NSURL(string: urlString)!
    }
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 懒加载控件
    private lazy var scrollView: UIScrollView = UIScrollView()
    lazy var imageView: UIImageView = UIImageView()
    /// 占位图片
    private lazy var placeHoder: ProgressImageView = ProgressImageView()
}
// MARK: - 设置控件
extension PhotoBrowerViewCell {
    private func setupUI() {
        // 添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(placeHoder)
        // 布局控件
        var rect = contentView.bounds
        rect.size.width -= 20
        scrollView.frame = rect
        
        // 设置 scrollView 缩放
        scrollView.delegate = self
        scrollView.maximumZoomScale = 2.0
        scrollView.minimumZoomScale = 0.5
        
        // 添加手势
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
}
// MARK: - UIScrollViewDelegate
extension PhotoBrowerViewCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    func scrollViewDidZoom(scrollView: UIScrollView) {
        print(imageView.frame)
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        var offsetX = (contentView.bounds.width - view!.frame.width) * 0.5
        offsetX = (offsetX < 0) ? 0 : offsetX
        var offsetY = (contentView.bounds.height - view!.frame.height) * 0.5

        offsetY = (offsetY < 0) ? 0 : offsetY
//        scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
        UIView.animateWithDuration(0.25) { () -> Void in
            view?.frame.origin = CGPointMake(offsetX, offsetY)
        }

    }
}
